package com.sweetguy.component;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.sweetguy.exception.ServiceException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Component
public class ServiceAspect {
    @Around("execution(public * com.sweetguy.service.impl.*.*(..))")
    @SneakyThrows
    public Object aroundAdvice(ProceedingJoinPoint pjp) {

        //
        Object[] args = pjp.getArgs();

        //
        String className = pjp.getTarget().toString();
        className = className.substring(className.lastIndexOf('.') + 1, className.indexOf('@'));
        String methodName = pjp.getSignature().getName();
        methodName = className + "." + methodName + "()";

        //
        if (ObjectUtil.hasNull(args)) {
            throw new ServiceException("业务方法" + methodName + "中存在null值参数");
        }

        //
        Object result = pjp.proceed(args);

        //
        log.info(String.format("\n" +
                        "================ 业务日志 ================\n" +
                        "业务方法: %s\n" +
                        "业务参数: %s\n" +
                        "响应数据: %s\n" +
                        "=====================================",
                methodName,
                JSONUtil.toJsonStr(args),
                JSONUtil.toJsonStr(result)));
        return result;
    }
}
